import {defineStore} from 'pinia';
import {reqLogin, reqLogout, reqUserInfo} from "../../api/userinfo.js";
import {ElMessage} from "element-plus";

export const useUserInfoStore = defineStore('userInfo', {
    state: () => ({
        token: "",
        userinfo: {
            name: ""
        }
    }),
    actions: {
        // 登录
        async setLogin(data) {
            let result = await reqLogin(data);
            if (result.token) {
                this.token = result.token
                localStorage.setItem('token',result.token);
                return 'ok'
            }
            return Promise.reject(new Error('登录失败'));
        },
        //退出登录
        async reset() {
            try {
                await reqLogout(); // 请求头携带token,告诉后端token作废
                localStorage.removeItem("token")// 删除local中保存的token
                // 清除store的token
                this.token = "";
            } catch (error) {
                ElMessage.error('退出登录错误')
                return Promise.reject(error);
            }
        },
        //获取用户信息
        async getInfo() {
            let result = await reqUserInfo();
            // console.log(result)// 请求头携带的
            console.log(this)
            this.userinfo.name = result.name;
        }
    }
})

